/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package apus.action.person;

import apus.action.Action;
import apus.action.ActionResult;
import apus.entity.Person;
import apus.entity.RealPerson;
import apus.persistence.PersonDAO;
import apus.services.ServiceLocator;
import java.io.UnsupportedEncodingException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author 21vek
 */
public class PersonSaveAction implements Action{

    @Override
    public String getName() {
        return "person.save";
    }

    @Override
    public ActionResult execute(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException ex) { }

        // if Save button have been pressed
        if (request.getParameter("saveButton") != null) {
            int id = Integer.parseInt(request.getParameter("id"));
            Person person = (id == 0) ? new RealPerson() : ServiceLocator.getService(PersonDAO.class).read(id);

            // load data from request
            person.setName(request.getParameter("name"));
            
            if (request.getParameter("passport")!=null){
                person.setPassportNumber(request.getParameter("passport"));
            }
            
            if (request.getParameter("address")!=null){
                person.setAddress(request.getParameter("address"));
            }

            PersonDAO personDAO = ServiceLocator.getService(PersonDAO.class);
            if (id != 0) {
                personDAO.update(person); // update
                request.getSession().setAttribute("win", person.getName()+" data was successfully updated");
            } else {
                personDAO.create(person); // create
                request.getSession().setAttribute("win", person.getName()+" was successfully added");
            }
        } else {
            request.getSession().setAttribute("fail", "Subscriber data wasn't saved");
        }
        List<Person> personList = ServiceLocator.getService(PersonDAO.class).findAll();
        request.setAttribute("personList", personList);
        return ActionResult.redirect("person.list");
    }
    
}
